package com.simtop.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.simtop.common.ServerResponse;
import com.simtop.dao.CountDao;
import com.simtop.mapper.UserMapper;
import com.simtop.pojo.ilabresultpo.IlabUser;
import com.simtop.pojo.userpo.User;
import com.simtop.pojo.userpo.Users;
import com.simtop.pojo.userpo.Userse;
import com.simtop.service.CjService;
import com.simtop.service.JwtLoginService;
import com.simtop.service.UserService;
import com.simtop.util.ilabutil.IlabUtil;
import com.simtop.util.jwtutil.JwtUtil;
import com.simtop.util.encryptionutil.SHA256Util;
import com.simtop.util.excelutil.ExcelUtils;
import com.simtop.vo.experiment.UserCj;
import com.simtop.vo.uservo.UserParamsVo;
import com.simtop.vo.uservo.UserVo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;


import java.util.List;

/**
 * @Author: liuzhaobo
 * @Description: 用户模块
 * @DateTime: 2022/8/31 0031 17:02
 * @Params:
 * @Return
 */
@Controller
@RequestMapping("/user")
@CrossOrigin //todo 跨域问题
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private JwtLoginService jwtLoginService;

    @Autowired
    private CountDao countDao;

    @Autowired
    private IlabUtil ilabUtil;

    @Autowired
    private ExcelUtils excelUtils;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CjService cjService;


    /**
     * @Author: liuzhaobo
     * @Description: iable登录
     * @DateTime: 2022/9/1 0001 10:13
     * @Params:
     * @Return
     */
    @RequestMapping(value = "/ilab/login", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> login(@RequestBody IlabUser ilabUser, HttpServletRequest request) {
        try {
            request.setCharacterEncoding("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        System.out.println("获取到的ilab参数token为：" + ilabUser.getToken());
        //获取ilab传递过来的token
        String token = ilabUser.getToken();
        try {
            /**
             * 调用ilab接口获取用户信息
             */
            String ilabJson = ilabUtil.getAccessToken(token);
            JSONObject o = JSONObject.parseObject(ilabJson);
            int code = o.getInteger("code");
            /**
             * 判断code不为0,则从ilab获取内容失败
             */
            if (code != 0) {
                return ServerResponse.createByErrorMsg("token失效，请重新通过ilab进入重做实验");
            }
            String loginName = o.getString("un");
            String username = o.getString("dis");
            //如果数据库存在登陆用户名 则直接返回
            User user = userService.selectUserByLoginName(loginName);
            if (user != null) {
                user.setAccessToken(URLEncoder.encode(o.getString("access_token"), "UTF-8"));
                String token1 = JwtUtil.sign(user, 60L * 1000L * 60L * 24);//token有效期24小时
                /**
                 * todo 统计网站访问次数：登陆成功后统计次数变量count加1
                 */
                int num = countDao.selectCount();
                int count = ++num;
                countDao.updateOne(count);
                return ServerResponse.createBySuccess(token1);
            }
            //不存在则在用户数据表中创建用户数据
            UserVo userVo = new UserVo();
            userVo.setLoginName(loginName);
            userVo.setUsername(username);
            userVo.setSchool("ilab平台用户");
            userVo.setProvince("ilab平台");
            userVo.setCity("ilab平台");
            //ilab用户身份
            userVo.setRoleId(5);
            userVo.setPassword(SHA256Util.generateShaPwd("12345"));
            userVo.setEmail("ilab@163.com");
            int resultCount = userService.insertIlabUser(userVo);
            //插入用户数据 给前端返回user的jwt对象
            User u = userService.selectUserByLoginName(userVo.getLoginName());
            //将access_token放入用户对象生成token
            u.setAccessToken(URLEncoder.encode(o.getString("access_token"), "UTF-8"));
            System.out.println(URLEncoder.encode(o.getString("access_token"), "UTF-8"));
            //24小时的token有效期
            String token1 = JwtUtil.sign(u, 60 * 60 * 1000 * 24L);
            int num = countDao.selectCount();
            int count = ++num;
            countDao.updateOne(count);
            return ServerResponse.createBySuccess(token1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ServerResponse.createByErrorMsg("新增ilab平台用户失败");
    }

    /**
     * @Author: liuzhaobo
     * @Description: 用户登录 返回唯一token
     * @DateTime: 2022/8/31 0031 15:13
     * @Params:
     * @Return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> login(@RequestBody UserVo userVo) {

        System.out.println("userVo" + userVo.getLoginName());
        System.out.println("userVoRoleId" + userVo.getRoleId());
        System.out.println("userVoPassword" + userVo.getPassword());

        if (userVo.getRoleId() == 1 || userVo.getRoleId() == 3) {
            User user = new User();
            //角色id
            user.setRoleId(userVo.getRoleId());
            //登录名
            user.setLoginName(userVo.getLoginName());
            //登陆密码
            user.setPassword(userVo.getPassword());
            return jwtLoginService.login(user);
        }
        User user = new User();
        //角色id
        user.setRoleId(userVo.getRoleId());
        //登录名
        user.setLoginName(userVo.getLoginName());
        //登陆密码
        user.setPassword(userVo.getPassword());
        return jwtLoginService.login(user);
    }

    /**
     * @Author: liuzhaobo
     * @Description: 专家登录 先成账号 然后返回唯一token
     * @DateTime: 2022/8/31 0031 15:12
     * @Params:
     * @Return
     */
    @RequestMapping(value = "/tourist", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> tourist() {
        UserVo loginUser = new UserVo();
        String s = UUID.randomUUID().toString();
        loginUser.setLoginName(s);
        loginUser.setUsername("评审专家");
        loginUser.setRoleId(3);
        loginUser.setSchool("高校学院");
        loginUser.setProvince("上海市");
        loginUser.setCity("浦东新区");
        loginUser.setPassword("123456");
        userService.insertBackUser(loginUser);
        User user = new User();
        //角色id
        user.setRoleId(3);
        //登录名
        user.setLoginName(s);
        //登陆密码
        user.setPassword("123456");
        return jwtLoginService.login(user);

    }

    /**
     * @Author: liuzhaobo
     * @Description: 获取邮箱验证码
     * @DateTime: 2022/8/31 0031 15:31
     * @Params:
     * @Return
     */
    @RequestMapping(value = "/checkCode", method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse<String> sendEmailCode(String email) {
        //根据邮箱获取验证码
        return userService.generateCheckCode(email);
    }


    /**
     * @Author: liuzhaobo
     * @Description: 注册
     * @DateTime: 2022/8/31 0031 15:23
     * @Params:
     * @Return
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> register(@RequestBody UserVo userVo) {
        System.out.println("接收到的前台参数为：" + userVo);
        return userService.register(userVo);
    }

    /**
     * @Author: liuzhaobo
     * @Description: 忘记密码时获取验证码 邮箱验证码
     * @DateTime: 2022/8/31 0031 15:57
     * @Params:
     * @Return
     */
    @RequestMapping(value = "/forget_checkCode", method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse<String> forgetSendEmailCode(String email) {
        //根据邮箱获取验证码
        return userService.forgetSendEmailCode(email);
    }

    /**
     * @Author: liuzhaobo
     * @Description: 更新密码 输入验证码
     * @DateTime: 2022/8/31 0031 16:01
     * @Params:
     * @Return
     */
    @RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> updatePassword(@RequestBody UserVo userVo) {
        return userService.updatePassword(userVo);
    }

    /**
     * 用户管理 查看所有的数据
     */
    @RequestMapping(value = "/backend/findAll", method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse<PageInfo<User>> findAll(HttpServletRequest request, Integer pageNum, Integer pageSize, String school) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        if (ObjectUtils.isEmpty(pageNum)) {
            pageNum = 1;
        }
        if (ObjectUtils.isEmpty(pageSize)) {
            pageSize = 10;
        }
        PageHelper.startPage(pageNum, pageSize);
        User user = new User();
        user.setRoleId(u.getRoleId());
        user.setSchool(school);
        System.out.println(user);
        List<User> userList = userService.findAll(user);
        PageInfo<User> pageInfo = new PageInfo<User>(userList);
        return ServerResponse.createBySuccess(pageInfo);
    }

    /**
     * 新增后台用户管理记录
     */
    @RequestMapping(value = "/backend/add", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> addUser(@RequestBody UserVo userVo, Integer userId, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        return userService.insertBackUser(userVo);
    }

    /**
     * @Author: liuzhaobo
     * @Description: 根据用户id删除user表
     * @DateTime: 2022/9/1 0001 9:49
     * @Params:
     * @Return
     */
    @RequestMapping(value = "/deleteByUserId", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> deleteById(@RequestBody String data, HttpServletRequest request) {
        /**
         * 解析参数
         */
        JSONObject jsonObject = JSONObject.parseObject(data);
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        Integer userId = jsonObject.getInteger("userId");
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        logger.info("管理员删除用户,编号为{}", userId);
        return userService.deleteByUserId(userId);
    }

    /**
     * 修改用户信息
     *
     * @param userVo
     * @param
     * @param request
     * @return
     */
    @RequestMapping(value = "/backend/update", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> updateBackendUser(@RequestBody UserVo userVo, HttpServletRequest request) {
        System.out.println("userId" + userVo);
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        return userService.updateBackendUser(userVo);
    }

    /**
     * @Author: liuzhaobo
     * @Description: 根据用户id查询用户信息
     * @DateTime: 2022/8/31 0031 17:53
     * @Params:
     * @Return
     */
    @RequestMapping(value = "/backend/findById", method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse<User> findUserById(HttpServletRequest request, Integer id) {
        String token = request.getHeader("Authorization");
        if (token == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        return userService.findById(id);
    }

    /**
     * @Author: liuzhaobo
     * @Description: 用户查询功能(学校, 姓名, 登录名查询)
     * @DateTime: 2022/8/31 0031 17:53
     * @Params:
     * @Return
     */
    @RequestMapping(value = "/backend/findByParams", method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse<PageInfo<User>> findByParams(HttpServletRequest request, UserParamsVo params, Integer pageNum, Integer pageSize) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        params.setRoleId(u.getRoleId());
        params.setUserId(u.getId());
        PageHelper.startPage(pageNum, pageSize);
        List<User> userList = userService.findByParams(params);
        PageInfo<User> pageInfo = new PageInfo<User>(userList);
        return ServerResponse.createBySuccess(pageInfo);
    }

    /**
     * @Author: liuzhaobo
     * @Description: 下载用户模板
     * @DateTime: 2022/8/31 0031 16:40
     * @Params:
     * @Return
     */
    @RequestMapping(value = "/backend/getUserTemplate", method = RequestMethod.GET)
    public void getUserTemplate(HttpServletRequest request, HttpServletResponse response) {
        excelUtils.cooperation(request, response, User.class, "上传用户模板");
    }

    /**
     * @Author: liuzhaobo
     * @Description: 批量上传用户
     * @DateTime: 2022/8/31 0031 16:41
     * @Params:
     * @Return
     */
    @PostMapping("/backend/importUser")
    @ResponseBody
    public ServerResponse<Object> importUsers(MultipartFile file) {
        List<Object> upload = excelUtils.upload(file, User.class);
        return userService.importUsers(upload);
    }

    /**
     * 获取模板 老师专用
     */
    @GetMapping("/getDemoByStudents")
    public void getUserTemplates(HttpServletRequest request, HttpServletResponse response) {
        excelUtils.cooperation(request, response, Userse.class, "上传用户模板");
    }


    /**
     * 上传接口老师用
     */
    @PostMapping("/importByStudent")
    @ResponseBody
    public ServerResponse<Object> importByStudent(MultipartFile file) {
        List<Object> upload = excelUtils.upload(file, Users.class);
        return userService.importUsers2(upload);
    }


    /**
     * @Author: liuzhaobo
     * @Description: 导出成绩
     * @DateTime: 2022/9/28 0028 14:49
     * @Params:
     * @Return
     */

    @RequestMapping(value = "/importStudent", method = RequestMethod.GET)
    public void importStudent(UserVo userVo, HttpServletRequest request, HttpServletResponse response) {
        List<UserCj> findall2 = cjService.findall2(userVo);
        excelUtils.cooperationData(request, response, findall2, "用户实验成绩", UserCj.class);
    }
}